""" 任务管理的相关接口 """
import json

from django.http import JsonResponse
from django.db.models import Q
from web.models import Order, Warehouse, Task
from datetime import datetime
import logging

system_logger = logging.getLogger('system_log')


def submit(request):
    """任务提交接口"""
    # 接收前端传递过来的值
    data = json.loads(request.body.decode("utf-8"))
    try:
        system_logger.info("__开始任务信息提交并保存数据库操作__")
        # task_id不为空时，更新数据库信息
        if data['task_id'] != '':
            update_data_task = Task.objects.get(task_id=data['task_id'])
            update_data_task.task_name = data['task_name']
            update_data_task.task_type = data['task_type']
            update_data_task.warehouse_id = data['warehouse_id']
            update_data_task.goods = data['goods']
            update_data_task.sourceOrDestination = data['sourceOrDestination']
            update_data_task.goods_num = data['goods_num']
            update_data_task.shippingMethod = data['shippingMethod']
            update_data_task.order_id = data['order_id']
            update_data_task.save()
        else:
            # 创建一个数据对象,新增数据信息
            add_data_task = Task(
                task_name=data['task_name'],
                task_type=data['task_type'],
                warehouse_id=data['warehouse_id'],
                goods=data['goods'],
                sourceOrDestination=data['sourceOrDestination'],
                goods_num=data['goods_num'],
                shippingMethod=data['shippingMethod'],
                order_id=data['order_id']
            )
            add_data_task.save()
        update_data_order = Order.objects.get(order_id=data['order_id'])
        update_data_order.state = data['order_state']
        update_data_order.save()

        update_data_warehouse = Warehouse.objects.get(warehouse_id=data['warehouse_id'])
        update_data_warehouse.state = data['warehouse_state']
        update_data_warehouse.save()
        system_logger.info("任务信息提交并保存数据库操作__成功")
        return JsonResponse({'code': '0', 'msg': "更新数据库成功！", 'data': "null"})

    except Exception as e:
        # return JsonResponse({'code': '1', 'msg': "更新数据库失败，具体原因：" + str(e)})
        system_logger.error(f"任务信息提交并保存数据库过程出错，具体原因是{e}__操作失败")
        return JsonResponse({'code': '1', 'msg': "更新数据库失败！", 'data': "null"})


def getInfo(request):
    """获取任务信息"""
    # 接收前端传递过来的值
    data = json.loads(request.body.decode("utf-8"))

    try:
        system_logger.info(f"__开始获取task_id为{data['task_id']}的任务信息操作__")
        result_objects = Task.objects.filter(Q(is_delete=0) & Q(task_id=data["task_id"]))
        # 构建结果列表

        for result in result_objects:
            data = {
                'task_id': result.task_id,
                'task_type': str(result.task_type),
                'task_name': result.task_name,
                'warehouse_id': result.warehouse_id,
                'goods': result.goods,
                'sourceOrDestination': result.sourceOrDestination,
                'goods_num': result.goods_num,
                'shippingMethod': str(result.shippingMethod),
                'order_id': result.order_id
            }
        system_logger.info(f"task_id为{data['task_id']}的任务信息获取操作__成功")
        return JsonResponse({'code': '0', 'msg': "查询成功！", 'data': data})

    except Exception as e:
        # return JsonResponse({'code': '1', 'msg': "查询成功失败，具体原因：" + str(e)})
        system_logger.error(f"task_id为{data['task_id为']}的任务信息获取过程出错，具体原因：{e}__操作失败")
        return JsonResponse({'code': '1', 'msg': "更新数据库失败！", 'data': "null"})


def search(request):
    """查询任务列表信息"""
    # 接收前端传递过来的值
    data = json.loads(request.body.decode("utf-8"))

    try:
        system_logger.info("__开始任务列表信息查询操作__")
        currentPage = data['currentPage']  # 当前界面
        pageSize = data['pageSize']  # 页面大小
        search = data['search']  # 关键字
        if search != '':

            result_objects = Task.objects.filter(
                (Q(task_name__icontains=search) | Q(goods__icontains=search) | Q(sourceOrDestination__icontains=search)
                 | Q(goods_num__icontains=search) | Q(order__commander__icontains=search)) & Q(is_delete=0))

            # 构建结果列表
            output = []
            for result in result_objects:
                data_dict = {
                    'task_id': result.task_id,
                    'task_type': result.task_type,
                    'task_name': result.task_name,
                    'warehouse_id': result.warehouse_id,
                    'goods': result.goods,
                    'sourceOrDestination': result.sourceOrDestination,
                    'goods_num': result.goods_num,
                    'shippingMethod': result.shippingMethod,
                    'order_id': result.order_id,
                    'commander': result.order.commander
                }
                result_objects_warehousename = Warehouse.objects.filter(warehouse_id=result.warehouse_id).values("warehouse_name").first()

                if result.task_type == 0:
                    data_dict["start_pos"] = result.sourceOrDestination
                    data_dict["end_pos"] = result_objects_warehousename['warehouse_name']
                else:
                    data_dict["start_pos"] = result_objects_warehousename['warehouse_name']
                    data_dict["end_pos"] = result.sourceOrDestination
                output.append(data_dict)
        else:
            result_objects = Task.objects.filter(is_delete=0).\
                select_related('order').values('task_id', 'task_type', 'task_name', 'warehouse_id', 'goods', 'goods_num'
                                               , 'sourceOrDestination', 'shippingMethod', 'order_id', 'order__commander')
            # 构建结果列表
            output = []
            for result in result_objects:
                data_dict = {
                    'task_id': result["task_id"],
                    'task_type': result["task_type"],
                    'task_name': result["task_name"],
                    'warehouse_id': result["warehouse_id"],
                    'goods': result["goods"],
                    'sourceOrDestination': result["sourceOrDestination"],
                    'shippingMethod': result["shippingMethod"],
                    'order_id': result["order_id"],
                    'commander': result["order__commander"]
                }
                result_objects_warehousename = Warehouse.objects.filter(warehouse_id=result["warehouse_id"]).\
                    values("warehouse_name").first()

                if result["task_type"] == 0:
                    data_dict["start_pos"] = result["sourceOrDestination"]
                    data_dict["end_pos"] = result_objects_warehousename["warehouse_name"]
                else:
                    data_dict["start_pos"] = result_objects_warehousename["warehouse_name"]
                    data_dict["end_pos"] = result["sourceOrDestination"]
                output.append(data_dict)
        # 计算总数
        count = result_objects.count()
        # 计算分页索引
        index_start = pageSize * (currentPage - 1)
        index_end = index_start + pageSize
        if index_start > count:
            return JsonResponse({'code': '1', 'msg': "查询失败，原因是分页参数错误"})
        else:
            data_list = output[index_start: index_end]
            data = {'data': data_list, 'total': count}
        if search != '':
            system_logger.info(f"与{search}关键字相关的任务信息查询操作__成功")
        else:
            system_logger.info("任务信息查询操作__成功")
        return JsonResponse({'code': '0', 'msg': "查询成功！", 'data': data})

    except Exception as e:
        # return JsonResponse({'code': '1', 'msg': "查询失败，具体原因：" + str(e)})
        system_logger.error(f"任务信息查询过程出错，具体原因：{e}__查询失败")
        return JsonResponse({'code': '1', 'msg': "更新数据库失败！", 'data': "null"})


def delete(request):
    """删除任务信息"""
    # 接收前端传递过来的值
    data = json.loads(request.body.decode("utf-8"))
    try:
        system_logger.info(f"__开始删除task_id为{data['task_id']}的任务信息操作__")
        delete_data = Task.objects.get(task_id=data['task_id'])
        # 查询需要删除的数据，真实删除
        # delete_data.delete()

        # 查询需要删除的数据，没有删除，只是修改了is_delete和delete_time字段
        delete_data.is_delete = 1
        delete_data.delete_time = datetime.now()
        delete_data.save()
        system_logger.info(f"删除task_id为{data['task_id']}的任务信息操作__成功")
        return JsonResponse({'code': '0', 'msg': "删除成功！", 'data': "null"})
    except Exception as e:
        # return JsonResponse({'code': '1', 'msg': "订单信息删除过程出错，具体原因：" + str(e)})
        system_logger.error(f"删除task_id为{data['task_id']}的任务信息操作过程出错，具体原因：{e}__操作失败")
        return JsonResponse({'code': '1', 'msg': "删除失败！", 'data': "null"})
